package com.rong.algorithm.search;

/**
 * 
 * @desc 二分查找法
 *
 * @author liurong
 *
 * @date 2020年6月29日
 */
public class BinarySearch {

	public static void main(String[] args) {
		int[] nums = { -1, 0, 3, 5, 9, 12 };
		BinarySearch binarySearch = new BinarySearch();
		System.out.println(binarySearch.search(nums, -2));
	}

	public int search(int[] nums, int target) {
		int left = 0;
		int right = nums.length;
		int mid = right / 2;
		int source;
		while ((source = nums[mid]) != target) {

			if (mid == left || mid == right) {
				return -1;
			}

			if (source == target) {
				break;
			} else if (source > target) {
				right = mid;
			} else {
				left = mid;
			}
			mid = (left + right) / 2;
		}
		return mid;
	}

}
